package com.example.yadmin.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.yadmin.common.utils.JwtUtil;
import com.example.yadmin.sys.entity.Menu;
import com.example.yadmin.sys.entity.User;
import com.example.yadmin.sys.entity.UserRole;
import com.example.yadmin.sys.mapper.UserMapper;
import com.example.yadmin.sys.mapper.UserRoleMapper;
import com.example.yadmin.sys.service.IMenuService;
import com.example.yadmin.sys.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ag
 * @since 2023-10-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private UserMapper userMapper;
    @Override
    public Map<String, Object> login(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //wrapper.eq("username","admin")属性名等于该值时
        wrapper.eq(User::getUsername,user.getUsername());
        //查询
        User loginUser = this.baseMapper.selectOne(wrapper);

        if (loginUser != null && passwordEncoder.matches(user.getPassword(),loginUser.getPassword())){
            //String value = "user:" + UUID.randomUUID();
            //存入redis
            //存入redis
            loginUser.setPassword(null);
            loginUser.setAvatar(null);
            //redisTemplate.opsForValue().set(value,loginUser,30, TimeUnit.MINUTES);

            //创建jwt
            String token = jwtUtil.createToken(loginUser);

            Map<String, Object> data= new HashMap<>();
            //将数据通过键值对方式添加到map里
            data.put("token",token);
            return data;
        }
        return null;
    }

//    @Override
//    public Map<String, Object> login(User user) {
//        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//        //wrapper.eq("username","admin")属性名等于该值时
//        wrapper.eq(User::getUsername,user.getUsername());
//        wrapper.eq(User::getPassword,user.getPassword());
//        //查询
//        User loginUser = this.baseMapper.selectOne(wrapper);
//
//        if (loginUser != null){
//            String value = "user:" + UUID.randomUUID();
//            //存入redis
//            //存入redis
//            loginUser.setPassword(null);
//            redisTemplate.opsForValue().set(value,loginUser,30, TimeUnit.MINUTES);
//
//            Map<String, Object> data= new HashMap<>();
//            //将数据通过键值对方式添加到map里
//            data.put("token",value);
//            return data;
//        }
//        return null;
//    }

    @Override
    public Map<String, Object> getUserInfo(String token) {
        //Object obj = redisTemplate.opsForValue().get(token);
        User loginUser = null;
        try {
            //解析出用户对象
            loginUser = jwtUtil.parseToken(token, User.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (loginUser != null){
            //User loginUser = JSON.parseObject(JSON.toJSONString(obj),User.class);
            Map<String, Object> data = new HashMap<>();
            data.put("id",loginUser.getId());
            data.put("name",loginUser.getUsername());
//            data.put("avatar",loginUser.getAvatar());

            //角色
            List<String> roleList = this.baseMapper.getRoleNameByUserId(loginUser.getId());
            data.put("roles",roleList);

            //权限列表
            List<Menu> menuList = menuService.getMenuListByUserId(loginUser.getId());
            data.put("menuList",menuList);

            return data;
        }
        return null;
    }

    @Override
    public void logout(String token) {
        //redisTemplate.delete(token);
    }

    @Override
    @Transactional
    public void addUser(User user) {
        //写入用户表
        this.baseMapper.insert(user);
        //写入用户角色表
        List<Integer> roleIdList = user.getRoleIdList();
        if (roleIdList != null){
            for (Integer roleId : roleIdList){
                userRoleMapper.insert(new UserRole(null,user.getId(),roleId));
            }
        }
    }

    @Override
    public User getUserById(Integer id) {
        User user = this.baseMapper.selectById(id);
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,id);
        List<UserRole> userRoleList = userRoleMapper.selectList(wrapper);

        List<Integer> roleIdList = userRoleList.stream()
                .map(userRole -> {return userRole.getRoleId();})
                .collect(Collectors.toList());
        user.setRoleIdList(roleIdList);
        return user;
    }

    @Override
    public void updateUser(User user) {
        //修改用户表
        this.baseMapper.updateById(user);
        //删除原有角色
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,user.getId());
        userRoleMapper.delete(wrapper);
        //设置新的角色
        List<Integer> roleIdList = user.getRoleIdList();
        if (roleIdList != null){
            for (Integer roleId : roleIdList){
                userRoleMapper.insert(new UserRole(null,user.getId(),roleId));
            }
        }
    }

    @Override
    public void deleteUserById(Integer id) {
        this.baseMapper.deleteById(id);
        //删除原有角色
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,id);
        userRoleMapper.delete(wrapper);
    }

    @Override
    public void updateMoney(User user) {
        this.baseMapper.updateById(user);
    }

    @Override
    public Integer getUserIdByUsername(String username) {
        Integer userId = this.baseMapper.getUserIdByUsername(username);
        return userId;
    }


}
